package com.macro.sms.utils;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.macro.sms.config.SmsTemplateCodeConfig;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

/**
 * @author ：小海
 * @dete ：2021-03-26 09:08:06
 * @Describe : 阿里云获取短信工具类
 */
@Slf4j
public class SmsUtil {

    //地域节点
    private static final String REGIONAL_NODE = "default";

    //产品域名,开发者无需替换
    private static final String DOMAIN = "dysmsapi.aliyuncs.com";

    // 需开发者指定accessKeyId
    private static  String accessKeyId = "配置accessKeyId";

    // 需开发者指定accessKeySecret
    private static String accessKeySecret = "配置accessKeySecret";



    public static boolean send(String phoneNumbers,String templateCode,Map<String,Object> param)  {


        DefaultProfile profile = DefaultProfile.getProfile(REGIONAL_NODE,accessKeyId,accessKeySecret);

        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();

        //request.setProtocol(ProtocolType.HTTPS);
        request.setSysMethod(MethodType.POST);
        request.setSysDomain(DOMAIN);
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");

        //手机号码
        request.putQueryParameter("PhoneNumbers",phoneNumbers);
        //阿里云的短信签名名称
        request.putQueryParameter("SignName","配置自己的签名名称");
        //阿里云的模版CODE
        request.putQueryParameter("TemplateCode",templateCode);
        //随机码格式为："{"code":"123456"}"
        request.putQueryParameter("TemplateParam", JSONObject.toJSONString(param));

        CommonResponse response = null;
        try {
            //调用阿里云接口发送短信
            response = client.getCommonResponse(request);
            log.info("获取信息："+response.getData());
        } catch (ServerException e){
            log.error("发送短信失败,获取错误信息："+e.getMessage());
        }catch (ClientException e) {
            log.error("发送短信失败,获取错误信息："+e.getMessage());
        }
        return response.getHttpResponse().isSuccess();
    }


    public static void main(String[] args) {

        //生成随机值，传递阿里云进行发送
        String code = RandomUtil.getFourBitRandom();

        //创建集合放入随机数
        Map<String, Object> param = new HashMap<>();
        param.put("code",code);
        //配置注册模板引擎
        boolean send = SmsUtil.send("配置手机号", SmsTemplateCodeConfig.registerTemplate, param);
        //配置登录模板引擎
        //boolean send = SmsUtil.send("配置手机号",SmsTemplateCodeConfig.loginTemplate, param);
        if (!send){
            log.error("短信发送失败");
        }
        log.info("短信发送成功, 验证码为:"+code);

    }
}
